package com.harmay.center.monitor.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zuper
 * @version 1.0
 * @date 2022/7/22 10:20
 */
@Slf4j
public class DingBotUtils {

    private static ObjectMapper jackson = JsonUtils.jackson();

    public static String URI_PREFFIX = "https://oapi.dingtalk.com/robot/send?access_token=";

    public static void sendMessage(String message, String accessToken, List<String> feedbackUsers) throws IOException {
        String uri = URI_PREFFIX + accessToken;
        Map<String, Object> map = Maps.newHashMap();
        map.put("msgtype", "text");
        if (CollectionUtils.isNotEmpty(feedbackUsers)) {
            map.put("at", new HashMap() {{
                put("atMobiles", feedbackUsers);
            }});
        }
        map.put("text", new HashMap<String, String>() {
            {
                put("content", message);
            }
        });
        String response = OkHttpUtils.post(jackson.writeValueAsString(map), uri);
        if ((int) JsonPath.read(response, "$.errcode") != 0) {
            log.warn("ding-bot response:{}", response);
        }
    }
}
